package com.nidu.demo.permission.query;

import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.nidu.demo.common.enums.MenuTypeEnum;
import com.nidu.demo.menu.convertor.MenuConvertor;
import com.nidu.demo.menu.dto.MenuTreeCO;
import com.nidu.demo.menu.model.Menu;
import com.nidu.demo.menu.util.MenuUtil;
import com.nidu.demo.permission.ability.PermissionDomainService;
import com.nidu.demo.role.model.Role;
import com.nidu.demo.user.dto.UserPermissionInfoCO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限单查询执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class PermissionSingleQryExe {

    private final PermissionDomainService domainService;

    private final MenuConvertor menuConvertor;

    public SingleResponse<UserPermissionInfoCO> getPermissionInfo(Long userId) {
        UserPermissionInfoCO info = new UserPermissionInfoCO();
        info.setUserId(userId);

        List<Role> roles = domainService.getActiveRoles(userId);
        info.setRoles(roles.stream().map(Role::getRoleCode).collect(Collectors.toList()));

        List<Menu> menus = domainService.getActiveMenus(userId);
        info.setButtons(menus.stream()
                .filter(m -> MenuTypeEnum.BUTTON.getType().equals(m.getMenuType()))
                .map(Menu::getPermission)
                .collect(Collectors.toList()));

        menus.removeIf(menu -> menu.getMenuType().equals(MenuTypeEnum.BUTTON.getType()));
        List<MenuTreeCO> menuTreeCOS = menuConvertor.toTreeClientObjects(menus);
        info.setMenus(MenuUtil.buildMenuTree(menuTreeCOS));
        return SingleResponse.of(info);
    }

    public MultiResponse<MenuTreeCO> getAccessibleMenus(Long userId) {
        List<Menu> menus = domainService.getActiveMenus(userId);
        menus.removeIf(menu -> menu.getMenuType().equals(MenuTypeEnum.BUTTON.getType()));
        List<MenuTreeCO> menuTreeCOS = menuConvertor.toTreeClientObjects(menus);
        return MultiResponse.of(MenuUtil.buildMenuTree(menuTreeCOS));
    }

    public SingleResponse<Boolean> hasAnyPermissions(Long userId, String[] permissions) {
        boolean result = domainService.hasAnyPermissions(userId, permissions);
        return SingleResponse.of(result);
    }

    public SingleResponse<Boolean> hasAnyRoles(Long userId, String[] roles) {
        boolean result = domainService.hasAnyRoles(userId, roles);
        return SingleResponse.of(result);
    }

}
